<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);

class video extends admin
{
    private $db;
    public $siteid;
    public $type;
    public $video;
    public $videos_collect;
    function __construct()
    {
        parent::__construct();
        pc_base::load_app_func('global');
        $this->db = pc_base::load_model('videos_model'); // 加载model
        $this->siteid = get_siteid(); // 获取当前站点
        $this->video = pc_base::load_model('video_nsr_model');
        $this->videos_collect = pc_base::load_model('videos_collect_model');
        $this->type = pc_base::load_model('source_type_model');
        $this->admin_username = param::get_cookie('admin_username'); // 获取当前登录的管理员
    }

    /**
     *视频集列表 
     **/
    public function init()
    {
        //如果没获取到 agency_id ，则视为非法请求
        if (! isset($_REQUEST['agency_id']) || empty($_REQUEST['agency_id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        //获取机构信息
        $id=$agency_id = $_REQUEST['agency_id'];
        $model_agency = pc_base::load_model('agency_nsr_model'); // 加载agency_model
        $data = $model_agency->get_one(array(
            'id' => $id
        ));

        //查询当前机构下的视频集
        $sql=" select v.* ,c.name as cname FROM nsrweb_videos as v LEFT JOIN nsrweb_agency  as c on c.id=v.agency_id";

        //拼装 where 查询语句
        $where = " where ";
        $show_dialog = $show_validator = true;
        $show_header = '';
        $where .= "v.status = 1 and v.agency_id = ".$id." and v.siteid =" . $this->siteid;


        // 搜索框
        $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';

        if (isset($_GET['search'])) {
            if ($keyword) {
                    $where .= " and v.name  like '%$keyword%'";
            }
        }

        $sql.=$where;
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;//获取分页码
        $agencyinfo = $this->db->my_listinfo($sql, $page, 10);
        //获取管理员信息
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $administrators = $admin_model->getRealnameInfo();
        //重构数据
        foreach ($agencyinfo as $key=>$value){
            foreach ($administrators as $key2=>$value2){
                if($value['updated_by'] == $key2){
                    $value['publisher'] = $value2;
                    $agencyinfo[$key] = $value;
                    break;
                }
            }
        }
        $pages = $this->db->pages;
        include $this->admin_tpl('video_list');
    }

    /**
     * 添加视频集
     */
    public function add()
    {
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);

            $data['created_by'] =  $_SESSION['userid'];
            $data['updated_by'] =  $_SESSION['userid'];

            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;//默认状态为1【状态（0：禁用  1：可用  2：删除）】
            $result = $this->db->insert($data);
            if ($result) {
                showmessage(L('add_success'), '?m=agency&c=video&a=init&agency_id='.$data['agency_id'],'','add');
            } else {
                showmessage(L('add_error'), HTTP_REFERER);
            }
        } else {
            $show_dialog = $show_validator = true;
            $show_header = '';
            if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
                showmessage(L('illegal_action'), HTTP_REFERER);
            }
            $id = $_REQUEST['id'];
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);
            include $this->admin_tpl('video_add');
        }
    }

    /**
     * 编辑视频集
     */
    public function edit()
    {
        //如果没获取到 id ，则视为非法请求
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
        $data = $this->db->get_one(array(
            'id' => $id
        ));
        $upinfo = $_POST['data'];
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['updated_by'] =  $_SESSION['userid'];
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;
            $result = $this->db->update($data, array(
                'id' => $id
            ));
            if ($result) {
                showmessage(L('edit_success'), '?m=agency&c=video&a=init&agency_id='.$data['agency_id'],'','edit');
            } else {
                showmessage(L('edit_error'), HTTP_REFERER);
            }
        } else {
            //$show_dialog = $show_validator = true;
            $show_dialog = $show_validator = true;
            $show_header = '';

            include $this->admin_tpl('video_edit');
        }
    }

    /**
     * 删除、批量删除视频集
     */
    public function del()
    {
        //如果没获取到 id ，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        //如果是多个，则处理数组
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        }
        $result = $this->db->update(array(
            'status' => '2'
        ), "id in ('$id')");
        if ($result) {
            showmessage(L('del_success'), HTTP_REFERER);
        } else {
            showmessage(L('del_error'), HTTP_REFERER);
        }
    }

    /*
     *视频集详情
     **/
    public function view()
    {
        //如果没获取到 agency_id ，则视为非法请求
        if (! isset($_REQUEST['agency_id']) || empty($_REQUEST['agency_id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        //资源类型，默认为1（资讯）
        $source_type=isset($_REQUEST['source_type'])?$_REQUEST['source_type']:1;
        $table="nsrweb_video_nsr";

        $id = $_REQUEST['id'];
        $agency_id = $_REQUEST['agency_id'];
        //查询机构信息
        $model_agency = pc_base::load_model('agency_nsr_model'); // 加载model
        $data = $model_agency->get_one(array(
            'id' => $agency_id
        ));
        //查询视频集信息
        $vieos_name = $this->db->get_one(array(
            'id' => $id
        ));
        $show_dialog = $show_validator = true;
        $show_header = '';
        //获取管理员信息
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $adminInfo = $admin_model->getRealnameInfo();
        //关联 1、视频集绑定视频表：nsrweb_videos_collect 、2、视频资源表：nsrweb_video_nsr 查出当前视频集所绑定的视频资源
        $sql="SELECT n.*,c.id as cid,c.updated_by as supdated_by  FROM nsrweb_videos_collect AS c LEFT JOIN ".$table." AS n ON c.video_id = n.id WHERE n.`status` = 1";

        // 搜索框
        $title = isset($_GET['title']) ? $_GET['title'] : '';
        if (isset($_GET['search'])) {
            if ($title) {
                $sql .= " and n.`title` LIKE '%$title%'";
            }
        }
        $sql.=" AND c.sid=".$id."  AND n.siteid = ".$this->siteid." ORDER BY  c.update_time desc";

        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;#获取分页码
        $sourceinfo = $this->db->my_listinfo($sql, $page, 10);
        $pages = $this->db->pages;
        include $this->admin_tpl('video_collect_list');
    }


    /**
     * 添加视频集
     */
    public function addVideo()
    {
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $this->video = pc_base::load_model('video_nsr_model');
            $model=$this->video;
            $information =$model->check($_POST['manage']);#添加公共信息
            $id = $model->edit($information);#入视频资源表：nsrweb_video_nsr
            //添加缓存
            // $this->news->redisCache($id);
            //建立绑定关系
            if ($id) {
                $data=array();

                $data['video_id']=$id;
                $data['sid']=$_POST['sid'];
                $data['created_by'] =  $_SESSION['userid'];
                $data['updated_by'] =  $_SESSION['userid'];

                $data['create_time'] = date("Y-m-d H:i:s",time());
                $data['update_time'] = date("Y-m-d H:i:s",time());
                $collect=pc_base::load_model('videos_collect_model'); // 加载model;
                $res = $collect->insert($data);
                if ($res) {
//                     showmessage(L('add_success'), '?m=agencyc=video&a=view&agency_id='.$_POST['agency_id'].'&id='.$_POST['sid'],'','add');
					showmessage(L('add_success').L('2s_close'),'blank','','','function set_time() {$("#secondid").html(1);}setTimeout("set_time()", 500);setTimeout("window.close()", 1200);');
                } else {
                    showmessage(L('add_error'), HTTP_REFERER);
                }
            } else {
                showmessage(L('add_information_error'), HTTP_REFERER);
            }
        } else {
            $show_dialog = $show_validator = true;
            $show_header = '';
            $types = $this->type->getSource(2);

            if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
                showmessage(L('illegal_action'), HTTP_REFERER);
            }
            $id= $_REQUEST['id'];
            $agency_id= $_REQUEST['agency_id'];
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);

            $action_source="agency_videos";
            include $this->admin_tpl('manage_add','video');


        }
    }

    /**
     * 批量删除视频集所绑定的视频
     * 备注：硬删除
     */
    public function deleteAll ()
    {
        $collect=pc_base::load_model('videos_collect_model'); // 加载model
        //提交表单
        if(isset($_GET['dosubmit'])) {
            $id = implode('\',\'', $_POST['ids']);
            //执行删除操作
            $result =$collect->delete("id in ('$id')");
            if ($result) {
                showmessage(L('del_success'), HTTP_REFERER);
            } else {
                showmessage(L('del_error'), HTTP_REFERER);
            }
        } else {
            showmessage(L('operation_failure'));
        }
    }

    /**
     * 批量删除视频集所绑定的视频
     * 备注：硬删除
     */
    public function delVideo()
    {
        $collect=pc_base::load_model('videos_collect_model'); // 加载model;
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        }
        $result = $collect->delete("id in ('$id')");


        if ($result) {
            showmessage(L('del_success'), HTTP_REFERER);
        } else {
            showmessage(L('del_error'), HTTP_REFERER);
        }
    }


    /*
     * 选择视频
     */
    public function bindView(){
        $id = (int)$_REQUEST['sid'];
        //如果没获取到 id ，则视为非法请求
        if (! isset($id) || empty($id)) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $source_type= 2;#视频资源
        //查询该视频集下已绑定的视频资源
        $source_array=$this->videos_collect->select(array("sid"=>$id),"video_id");
        //where 查询
        $where=" status=1 and  siteid =" . $this->siteid;

        // 搜索框
        $keywords = isset($_GET['keywords']) ? $_GET['keywords'] : '';
        $typeid = isset($_GET['typeid']) ? $_GET['typeid'] : '';
        if (isset($_GET['search'])) {
            if ($keywords) {
                $where .= " and `title` LIKE '%$keywords%'";
            }
            if ($typeid) {
                $where .= " and type_id = {$typeid}";
            }
        }
        //资源类型
        $select_categorys = $this->type->getSource($source_type,$typeid);
        //去重复
        if(!empty($source_array)){
            foreach ($source_array as $k => $v) {
                $sid[] = intval($v['video_id']);
            }
            $sid = implode('\',\'', $sid);
            $where.=" and id not in ('$sid')";
        }

        
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;//获取分页码
        $model=$this->video;
        //$url用在弹出页面中的“一键导入”，拼装地址
        $url = "?m=agency&c=video&a=bindTypeSource&sid=".$id;
        $show_dialog = $show_validator = true;
        $show_header = '';
        //获取管理员信息
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $adminInfo = $admin_model->getRealnameInfo();
        $sid=$id;
        $infos=$model->listinfo($where,'id DESC',$page,10);#默认按照资源的ID降序排列
        $pages = $model->pages;
        include $this->admin_tpl('video_select','video');
    }

    /**
     * ajax一键导入类型下资源
     */
    public function bindTypeSource ()
    {
        $sid = (int)$_REQUEST['sid'];#获取视频集ID
        //如果没获取到 sid，则视为非法请求
        if (! isset($sid) || empty($sid)) {
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"非法请求！"));
            exit();
        }
        $type_id = (int) $_REQUEST['type_id'];#资源分类id
        $typeInfo = $this->type->get_one(array('id'=>$type_id));#获取该分类信息
        $model=$this->video;
        $info_type='视频';
        //查询当前视频集已绑定视屏资源的id，列表去重复
        $video_id = $this->videos_collect->select(array('sid'=>$sid),'video_id');
        if(!empty($video_id)){
            $sqltmp = ' id not in (';
            foreach ($video_id as $ks=>$vs){
                $sqltmp .= "'".$vs['video_id']."',";
            }
            $sqltmp = substr($sqltmp, 0, -1);
            $sqltmp .=') and type_id='.$type_id;
        }else{
            $sqltmp = 'type_id='.$type_id;
        }
        //若 $typeInfo['parentid'] 为 0，说明为父级分类
        if ($typeInfo['parentid'] > 0) {
            $info = $model->select($sqltmp,'id');#查询出尚未绑定的视频ID
            //数据重构，入库
            $data=array();
            foreach($info as $k=>$v){
                $data[$k]['video_id']=$v['id'];
                $data[$k]['sid']=$sid;
                $data[$k]['created_by'] =  $_SESSION['userid'];
                $data[$k]['updated_by'] =  $_SESSION['userid'];

                $data[$k]['create_time'] = date("Y-m-d H:i:s",time());
                $data[$k]['update_time'] = date("Y-m-d H:i:s",time());
            }
            $res=$this->videos_collect->multiInsert($data);
//             echo  json_encode(array("status"=>true,"code"=>1000,"msg"=>$type_id));
//             exit();
            if($res){
                echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"一键导入成功！"));
            }else{
                echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"一键导入失败！"));
            }
        } else {
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"请选择".$info_type."的二级分类 ！"));
        }
    }


    /*
     * 视频集与视频资源绑定（含批量绑定）
     */
    public function  bindAction(){
        $id= $_REQUEST['id'];
        //如果没获取到 id，则视为非法请求
        if (! isset($id) || empty($id)) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $relation=$_REQUEST['relation'];#获取选中的视频ID
        $source=explode("|",$relation);
        //数据重构，入库
        $data=array();
        $collect=pc_base::load_model('videos_collect_model'); // 加载 videos_collect_model
        foreach($source as $k=>$v){
            $data[$k]['sid']=$id;
            $data[$k]['video_id']=$v;
            $data[$k]['created_by'] =  $_SESSION['userid'];
            $data[$k]['updated_by'] =  $_SESSION['userid'];
            $data[$k]['create_time'] = date("Y-m-d H:i:s",time());
            $data[$k]['update_time'] = date("Y-m-d H:i:s",time());
        }
        $res=$this->videos_collect->multiInsert($data);
        if($res){
            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"选择成功"));
        }else{
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"选择失败"));
        }
    }



}